<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="报价单号" prop="productNum">
        <el-input
          v-model="queryParams.bjdH"
          placeholder="报价单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建日期" prop="createDate">
        <el-date-picker
          v-model="queryParams.createDate"
          type="date"
          placeholder="选择日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['sales:price:add']"
        >创建报价单</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
        >导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['sales:price:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['sales:price:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="priceList" @selection-change="handleSelectionChange" :row-class-name="tableRowClassName">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="公司名称" align="center"width="80" prop="factoryNo" />
      <el-table-column label="报价单号" align="center"width="150" prop="bjdH" />
      <el-table-column label="物料名称" align="center"width="150" prop="productName" />
      <el-table-column label="规格型号" align="center" width="230" prop="specification" show-overflow-tooltip/>
      <el-table-column label="客户名称" align="center" prop="clientName" width="230" show-overflow-tooltip/>
      <el-table-column label="外径(mm)" align="center" prop="outDia" width="100"/>
      <el-table-column label="内径(mm)" align="center" prop="innerDia" width="100" />
      <el-table-column label="法兰厚度(mm)" align="center" prop="flThick" width="120"/>
      <el-table-column label="理论重量" align="center" prop="bzsl" />
      <el-table-column label="材料成本价(元)" align="center" prop="clcbj" width="110"/>
      <el-table-column label="加工成本价(元)" align="center" prop="jgcbj" width="110"/>
      <el-table-column label="密封槽成本价(元)" align="center" prop="mfccbj" width="120"/>
      <el-table-column label="订单数量系数(小数)" align="center" prop="ddslxs" width="140"/>
      <el-table-column label="加工难度系数(小数)" align="center" prop="jgndxs" width="140"/>
      <el-table-column label="合计成本价(元)" align="center" prop="hjcbj" width="110"/>
      <el-table-column label="订单数量" align="center" prop="orderNum" width="100"/>
      <el-table-column label="下料重量" align="center" prop="xlzl" width="100"/>
      <el-table-column label="理论报价(元)" align="center" prop="llbj" width="100">
        <template slot-scope="scope">
          <span>{{scope.row.llbj | numFilter}}</span>
        </template>
      </el-table-column>
      <el-table-column label="实际报价(元)" align="center" prop="sjbj" width="100">
        <template slot-scope="scope">
          <span>{{scope.row.sjbj | numFilter}}</span>
        </template>
      </el-table-column>
      <el-table-column label="税率" align="center" prop="taxRate" width="100"/>
      <el-table-column label="含税报价(元)" align="center" prop="hsbj" width="100"/>
      <el-table-column label="创建时间" align="center" prop="createTime" width="160"/>
      <el-table-column label="创建人" align="center" prop="createBy" width="100"/>
      <el-table-column label="操作" align="center"  fixed="right" class-name="small-padding fixed-width" width="120">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            v-show="scope.row.schtbj==0"
            icon="el-icon-edit"
            @click="change(scope.row)"
            v-hasPermi="['sales:price:edit']"
          >编辑</el-button>
          <el-button
            size="mini"
            type="text"
            v-show="scope.row.schtbj==0"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['sales:price:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改入库单对话框 -->
    <el-dialog :close-on-click-modal="false" :title="title" :visible.sync="open" width="1500px" append-to-body>
      <el-form ref="bjForm" :model="form" :rules="rules" label-width="150px">
<!--        报价单位 接收单位 报价人 报价时间-->

        <el-row>
          <el-col :span="12">
            <el-form-item label="报价单号" prop="bjdh">
              <el-input style="width: 80%" v-model="this.form.bjdH" placeholder="请输入报价单位" readonly></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="有效时长" prop="bjyxsj">
              <el-input style="width: 80%" v-model="form.bjyxsj" placeholder="请输入报价时长">
                <template slot="append">天</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="报价单位" prop="bjdw">
              <el-input style="width: 80%" v-model="this.bjdw" placeholder="请输入报价单位"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户名称" prop="unit">
              <el-select v-model="form.unit" placeholder="请选择接收单位" clearable>
                <el-option
                  v-for="item in this.clientList"
                  :key="item.clientCode"
                  :label="item.clientName"
                  :value="item.clientCode"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="报价人" prop="bjr">
              <el-input style="width: 80%" v-model="form.bjr" placeholder="请输入报价人" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="报价日期" prop="bjDate">
              <el-date-picker clearable
                              v-model="form.bjDate"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="请选择报价时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <bjglAdd ref="bjglAdd"></bjglAdd>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog :close-on-click-modal="false" :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <!--  <div class="el-upload__tip" slot="tip">
              <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据
            </div>-->
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :close-on-click-modal="false" title="修改报价单" :visible.sync="changeOpen" width="400px" append-to-body>
      <el-form :model="form2" ref="queryForm3" size="small" :inline="true" v-show="showSearch" label-width="100px">
        <el-form-item label="订单数量" prop="orderNum">
          <el-input v-model="form2.orderNum" placeholder="请输入订单数量"/>
        </el-form-item>
        <el-form-item label="税率" prop="taxRate">
          <el-input v-model="form2.taxRate" placeholder="请输入税率" @input="changeTaxRate"/>
        </el-form-item>
        <el-form-item label="实际报价" prop="sjbj">
          <el-input v-model="form2.sjbj" placeholder="请输入实际报价" readonly/>
        </el-form-item>
        <el-form-item label="含税报价" prop="hsbj" >
          <el-input v-model="form2.hsbj" readonly/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm22">确 定</el-button>
        <el-button @click="changeOpen = false">取 消</el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script>
import {delPrice, addPrice, updatePrice, listRules, genBjNumber, getInfoByDh, getPrice} from "@/api/sales/price";
import bjglAdd from "./bjglAdd";
import {lisAllFiles, listFiles} from "@/api/sales/clientFiles";
import {getToken} from "@/utils/auth";
import moment from 'moment';
import {updateItembzinfo} from "@/api/base/itembzinfo";
import {getSalesorder} from "@/api/sales/salesorder";
import {getLiSupplier} from "@/api/supplychain/supplier";

export default {
  components: {
    bjglAdd
  },
  name: "bjrules_index",
  data() {
    return {
      options1: [{
        value: '1',
        label: '有效'
      }, {
        value: '0',
        label: '无效'
      }],
      options2: [{
        value: '0',
        label: '未生成'
      }, {
        value: '1',
        label: '已生成'
      }],
      changeOpen:false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      bjdH:[],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      bjdw:"泰康铸造股份有限公司",
      // 报价单表格数据
      priceList: [],
      clientList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        factoryNo: null,
        productNo: null,
        productZhNo: null,
        productNum: null,
        productSubNum: null,
        productName: null,
        productBarcode: null,
        materialCategory: null,
        specification: null,
        unit: null,
        bjdH: null,
        deviceNo: null,
        devicePower: null,
        outDia: null,
        innerDia: null,
        flThick: null,
        lskj: null,
        lskjNum: null,
        ttWj: null,
        ttNj: null,
        ttHd: null,
        jstj: null,
        jszl: null,
        bzsl: null,
        cldj: null,
        clcbj: null,
        jgcbj: null,
        mfccbj: null,
        ddslxs: null,
        jgndxs: null,
        hjcbj: null,
        tzxs: null,
        llbj: null,
        sjbj: null,
        accountDate: null,
        bjDate: null,
        bjr: null,
        pzr: null,
        bjyxsj: null,
        bjyxsjbj: null,
        schtbj: null,
        createDate:new Date()
      },
      supplyList:[],
      form2:{},
      // 表单参数
      form: {
        codeParams:[],
        bjDate:new Date(),
        bjyxsj:15,
        htdH:''
      },
      // 客户导入参数
      upload: {
        // 是否显示弹出层（物料导入）
        open: false,
        // 弹出层标题（物料导入）
        title: "导入报价信息",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/sales/price/importData"
      },
      bjForm:{

      },
      // 表单校验
      rules: {
        unit: [
          { required: true, message: "请选择接收单位", trigger: "blur" }
        ],
        bjr: [
          { required: true, message: "请填写报价人", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    // console.log(new Date(),"ss")
    // this.$set(this.queryParams, "createDate", new Date());
    this.getList();
  },
  filters: {
    numFilter (value) {
      // 截取当前数据到小数点后两位
      let realVal = parseFloat(value).toFixed(2)
      return realVal
    }
  },
  methods: {
    submitFileForm22(){
      updatePrice(this.form2).then(response => {
        this.$modal.msgSuccess("修改成功");
        this.changeOpen = false;
        this.getList();
      });
    },
    tableRowClassName({row, rowIndex}) {
      if (row.schtbj === '0') {
        return 'warning-row';
      }
      return '';
    },
    change(row){
      console.log(row)
      this.reset();
      const id = row.id || this.ids
      getPrice(id).then(response => {
        console.log(response.data)
          this.form2 = response.data;
          this.changeOpen=true
          this.title = "编辑信息";
      });

    },
    /** 查询报价单列表 */
    getList() {
      this.loading = true;
      this.queryParams.createDate = moment.utc(this.queryParams.createDate).local().format('YYYY-MM-DD')
      if(this.queryParams.createDate == 'Invalid date'){
        this.queryParams.createDate = null
      }
      listRules(this.queryParams).then(response => {
        this.priceList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        factoryNo: null,
        productNo: null,
        productZhNo: null,
        productNum: null,
        productSubNum: null,
        productName: null,
        productBarcode: null,
        materialCategory: null,
        specification: null,
        unit: null,
        deviceNo: null,
        devicePower: null,
        outDia: null,
        innerDia: null,
        flThick: null,
        lskj: null,
        lskjNum: null,
        ttWj: null,
        ttNj: null,
        ttHd: null,
        jstj: null,
        jszl: null,
        bzsl: null,
        cldj: null,
        clcbj: null,
        jgcbj: null,
        mfccbj: null,
        ddslxs: null,
        jgndxs: null,
        hjcbj: null,
        tzxs: null,
        llbj: null,
        sjbj: null,
        accountDate: null,
        bjDate: new Date(),
        bjr: null,
        pzr: null,
        bjyxsj: 15,
        bjyxsjbj: null,
        schtbj: null,
        remark: null
      };
      this.resetForm("form");
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.bjdH = selection.map(item => item.bjdH)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.open = true;
      this.title = "添加报价规则";
      lisAllFiles().then(res=>{
        genBjNumber().then(response=>{
          this.form.bjdH = response.data;
          this.clientList=res.rows;
        });
      });

      setTimeout(() => {
        this.$refs.bjglAdd.rukuinfoAddListReset();
      }, 10);

    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const bjdH = row.bjdH || this.bjdH
      getInfoByDh(bjdH).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "编辑报价单";
      });
    },
    /** 提交按钮 */
    submitForm() {
      let itembzinfoList= this.$refs.bjglAdd.itembzinfoList;
      console.log(itembzinfoList,"itembzinfoList")
      this.form.infoList=itembzinfoList;
      if(itembzinfoList.length==0){
        this.$modal.alertWarning('请选择物料')
        return;
      }
      for(var i=0;i<itembzinfoList.length;i++) {
        if (itembzinfoList[i].clcbj == '' || itembzinfoList[i].clcbj == null || itembzinfoList[i].clcbj == undefined) {
          this.$modal.alertWarning('请输入材料成本价')
          return;
        }
        if (itembzinfoList[i].jgcbj == '' || itembzinfoList[i].jgcbj == null || itembzinfoList[i].jgcbj == undefined) {
          this.$modal.alertWarning('请输入加工成本价')
          return;
        }
        // if (itembzinfoList[i].mfccbj == '' || itembzinfoList[i].mfccbj == null || itembzinfoList[i].mfccbj == undefined) {
        //   this.$modal.alertWarning('请输入密封槽成本价')
        //   return;
        // }
        // if (itembzinfoList[i].orderNumCoe == '' || itembzinfoList[i].orderNumCoe == null || itembzinfoList[i].orderNumCoe == undefined) {
        //   this.$modal.alertWarning('请输入订单数量系数')
        //   return;
        // }
        if (itembzinfoList[i].xlzl == '' || itembzinfoList[i].xlzl == null || itembzinfoList[i].xlzl == undefined) {
          this.$modal.alertWarning('请输入下料重量')
          return;
        }
        if (itembzinfoList[i].hjcbj == '' || itembzinfoList[i].hjcbj == null || itembzinfoList[i].hjcbj == undefined) {
          this.$modal.alertWarning('请输入合计成本价')
          return;
        }
        // if (itembzinfoList[i].tzxs == '' || itembzinfoList[i].tzxs == null || itembzinfoList[i].tzxs == undefined) {
        //   this.$modal.alertWarning('请输入调整系数')
        //   return;
        // }
        if (itembzinfoList[i].llbj == '' || itembzinfoList[i].llbj == null || itembzinfoList[i].llbj == undefined) {
          this.$modal.alertWarning('请输入理论报价')
          return;
        }
        if (itembzinfoList[i].sjbj == '' || itembzinfoList[i].sjbj == null || itembzinfoList[i].sjbj == undefined) {
          this.$modal.alertWarning('请输入实际报价')
          return;
        }
        // if (itembzinfoList[i].taxRate == '' || itembzinfoList[i].taxRate == null || itembzinfoList[i].taxRate == undefined) {
        //   this.$modal.alertWarning('请输入税率')
        //   return;
        // }
        if (itembzinfoList[i].hsbj == '' || itembzinfoList[i].hsbj == null || itembzinfoList[i].hsbj == undefined) {
          this.$modal.alertWarning('请输入含税报价')
          return;
        }
      }
      let ifChangeXlzlValue= this.$refs.bjglAdd.ifChangeXlzlValue;
      if(ifChangeXlzlValue.length>0){
        this.$modal.confirm('是否同步修改标准物料表中下料重量的数据？').then(function() {
          for(let i=0;i<ifChangeXlzlValue.length;i++){
            updateItembzinfo(ifChangeXlzlValue[i]);
          }
        }).catch(() => {
        });
      }
      this.$refs["bjForm"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updatePrice(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPrice(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });

    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除报价单编号为"' + ids + '"的数据项？').then(function() {
        return delPrice(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('sales/price/export', {
        ...this.queryParams
      }, `报价单${new Date().getTime()}.xlsx`)
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "客户导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('sales/price/importTemplate', {
      }, `报价模板.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    changeTaxRate(e){
      this.form2.hsbj = (this.form2.sjbj/(1-e)).toFixed(2);
    }
  },

};
</script>

<style>
.el-table .warning-row {
  background: oldlace;
}

.el-table .success-row {
  background: #f0f9eb;
}
</style>

